from flask import  Flask, render_template,request,escape
import requests
import matplotlib.pyplot as plt
import json
from weatherapi import weather

app = Flask(__name__)
def log_request(req:"flask request",res:str):
	with open("vsearch.log","a") as log:
		print(req.form,req.host_url,req.remote_addr,file=log,sep="|")


# @app.route('/search',methods = ['POST'])
# def search():
# 	phrase = request.form.get("phrase")
# 	letters = request.form.get("letters")
# 	results=phrase+letters
# 	log_request(request,results)
# 	title = "Here are your results"
# 	return render_template("results.html",the_title=title,the_phrase=phrase,the_letters=letters,the_results=results)
	
@app.route('/entry',methods=['post','get'])
def hello_entry():
	user = request.form.get("user")
	log_request(request,user)
	return render_template('entry.html',the_title='图片识别网')

@app.route("/login",methods=['get'])
def index()-> 'html':
	title ='welcome'
	return render_template("login.html",the_title=title)


@app.route("/remote",methods=["post"])
def remote():
	image_url=request.form['remote']
	endpoint = "https://cvhzx.cognitiveservices.azure.com/"
	subscription_key = "236e247ef32e4f61a71202de77cb8266"
	analyze_url = endpoint + "vision/v3.1/analyze"   
	headers = {'Ocp-Apim-Subscription-Key': subscription_key}
	params = {'visualFeatures': 'Categories,Description,Color'}
	data = {'url': image_url}
	response = requests.post(analyze_url, headers=headers,  params=params, json=data)
	response.raise_for_status()
	analysis = response.json()
	print(json.dumps(response.json()))
	image_caption = analysis["description"]["captions"][0]["text"].capitalize()
	confidence3 = analysis["description"]["captions"][0]["confidence"]
	return render_template('entry.html',remote=str(image_caption),confidence3=str(confidence3),img_url1=image_url)

	

@app.route("/items",methods=["POST"])
def items():
	image_url=request.form["items"]
	landmark_analyze_url = 'https://cvhzx.cognitiveservices.azure.com/' + "vision/v3.1/models/landmarks/analyze"
	subscription_key='7388368827d942c5b517d8c6218ef191'
	headers = {'Ocp-Apim-Subscription-Key': subscription_key}
	params = {'model': 'landmarks'}
	data = {'url': image_url}
	response = requests.post(
    landmark_analyze_url, headers=headers, params=params, json=data)
	response.raise_for_status()
	analysis = response.json()
	assert analysis["result"]["landmarks"] is not []
	print(analysis)
	landmark_name = analysis["result"]["landmarks"][0]["name"].capitalize()
	confidence=analysis["result"]["landmarks"][0]["confidence"]
	return render_template('entry.html', items=str(landmark_name),confidence1=str(confidence),img_url2=image_url)

@app.route("/person",methods=["POST"])
def person():
	image_url=request.form["person"]
	subscription_key = "7388368827d942c5b517d8c6218ef191"
	assert subscription_key
	vision_base_url = "https://cvhzx.cognitiveservices.azure.com/vision/v2.1/"
	celebrity_analyze_url = vision_base_url + "models/celebrities/analyze"
	headers = {'Ocp-Apim-Subscription-Key': subscription_key}
	params = {'model': 'celebrities'}
	data = {'url': image_url}
	response = requests.post(celebrity_analyze_url, headers=headers, params=params, json=data)
	response.raise_for_status()
	analysis = response.json()
	celebrity_name = analysis["result"]["celebrities"][0]["name"].capitalize()
	confidence2=analysis["result"]["celebrities"][0]["confidence"]
	return render_template('entry.html',person=str(celebrity_name),confidence2=str(confidence2),img_url3=image_url)

@app.route("/we",methods=["post"])
def we():
	key='18ef7dd6aeefc21dade574262c00f213'
	city='440100'
	extensions='base'
	a=weather(key,city,extensions)
	b=a['lives'][0]['city']
	c=a['lives'][0]['weather']
	d=a['lives'][0]['temperature']
	return render_template('entry.html',city=str(b),weather=str(c),temperature=str(d))

@app.route("/viewlog")
def view_log():
	contents=[]
	with open("vsearch.log","r") as log:
		for line in log:
			contents.append([])
			for item in line.split("|"):
				contents[-1].append(escape(item))
		titles= ["Formdata","Host_url","Remote_addr"]
	return render_template('view.html',the_data=contents,the_titles=titles)
	

if __name__ == '__main__':
	app.run(debug= True)

